package com.bdtop.dbl.ui.activities.device;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.ZoomControls;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.bdtop.dbl.BaseActivity;
import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.R;
import com.bdtop.dbl.model.DeviceInfo;
import com.bdtop.dbl.model.Fence;
import com.bdtop.dbl.model.Position;
import com.bdtop.dbl.server.ServerApiFactory;
import com.bdtop.dbl.server.response.BaseResponse;
import com.bdtop.dbl.server.response.PositionResponse;
import com.bdtop.dbl.thirdparty.asynchttp.RequestCallback;
import com.bdtop.dbl.ui.view.MLinearLayout;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.DBLDebug;
import com.bdtop.dbl.utils.NetworkUtils;
import com.bdtop.dbl.utils.Preferences;

/**
 * @ClassName: AddFenceActivity
 * @Description: TODO
 * @author: wangpeng
 * @date:2014-10-13
 */
public class FenceModiActivity extends BaseActivity {

	private EditText etFenceName;
	private SeekBar sbDistance;

	private MapView mMapView;
	private BaiduMap mBaiduMap;
	private MarkerOptions mMarkerOptions;

	public static final String EXTRA_FENCE = "fence";
	public static final String EXTRA_MDN = "extra_mdn";

	private static final int seek_bar_start = 200;
	private static final int seek_bar_default_value = 600;
	private static final int seek_bar_progress = 4800;

	private int currentRadius = seek_bar_default_value;

	private String mdn;
	private String sign;
	private Fence fence;
	private LatLng mDevicePoint;

	private String state;
	private final String STATE_SAVE = "state_save";
	private final String STATE_UPDATE = "state_update";

	private Button btnAdd;

	public static final void launch(Context context, Fence fence, String mdn) {
		Intent intent = new Intent(context, FenceModiActivity.class);
		intent.putExtra(EXTRA_FENCE, fence);
		intent.putExtra(EXTRA_MDN, mdn);
		context.startActivity(intent);
		((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.keep_original_state);
	}

	@Override protected void onStart() {
		super.onStart();
		// mdn = DBLApplication.getInstance().currentDeviceMdn;
		mdn = getIntent().getStringExtra(EXTRA_MDN);
		// mdn = Preferences.getCurrentDeviceMdn(getApplicationContext());
		sign = Preferences.getLoginSign(getApplicationContext());
		fence = (Fence) getIntent().getSerializableExtra(EXTRA_FENCE);

		if (fence == null) {
			state = STATE_SAVE;
			moveToSelfForWaitCallback();
			setTitleText(R.string.add_fence_title);
			DeviceInfo mdi = null;
			if (DBLApplication.getInstance().deviceInfoList != null) {
				for (DeviceInfo di : DBLApplication.getInstance().deviceInfoList) {
					if (di.mdn.equals(mdn)) {
						mdi = di;
						break;
					}
				}
			}
			if (mdi != null && mdi.pos != null) {
				mDevicePoint = new LatLng(mdi.pos.lat, mdi.pos.lon);
				searchDevicePointOnMap();
				drawFenceOnMap(seek_bar_default_value);
			} else {
				setAndShowWaitingMessage(R.string.device_location_waiting);

				ServerApiFactory.getApiImpl().getPosition(sign, mdn, new RequestCallback() {
					@Override public void onSuccess(String rawData, Object response) {
						clearAndHiddenWaitingMessage();

						PositionResponse positionResponse = (PositionResponse) response;

						String status = positionResponse.getStatus();

						if (Constants.REQUEST_SUCCESS.equals(status)) {
							Position p = positionResponse.getPos();
							mDevicePoint = new LatLng(p.getLat(), p.getLon());
							searchDevicePointOnMap();
							drawFenceOnMap(seek_bar_default_value);
						} else {
							if (mDevicePoint == null) {
								setAndShowWaitingMessage(R.string.fail_deivce_position);
							}
						}
					}

					@Override public void onError(int statusCode, Throwable e, String rawData) {
						clearAndHiddenWaitingMessage();
						if (NetworkUtils.isNetConnect(getApplicationContext())) {
							showToast(R.string.oper_error);
						} else {
							showToast(R.string.net_error);
						}
					}
				});
			}
		} else {
			state = STATE_UPDATE;
			setTitleText(R.string.edit_fence_title);
			clearAndHiddenWaitingMessage();
			String fencename = fence.getFence_name();
			etFenceName.setText(fencename);
			double lat = Double.parseDouble(fence.getLat());
			double lon = Double.parseDouble(fence.getLon());
			etFenceName.setText(fence.getFence_name());
			mDevicePoint = new LatLng(lat, lon);
			searchDevicePointOnMap();
			currentRadius = Integer.parseInt(fence.getRadius());
			drawFenceOnMap(currentRadius - seek_bar_start); // fix 每次围栏变大一点。
		}

	}

	private void moveToSelfForWaitCallback() {
		String[] latlng = Preferences.getLastSelfLocation(FenceModiActivity.this);
		if (latlng != null) {
			LatLng point = new LatLng(Double.parseDouble(latlng[0]), Double.parseDouble(latlng[1]));
			MapStatusUpdate m = MapStatusUpdateFactory.newLatLng(point);
			mBaiduMap.animateMapStatus(m);
		}
	}


	@Override protected void onCreate(Bundle savedInstanceState) {
		MLinearLayout mLinearLayout = (MLinearLayout) LayoutInflater.from(this).inflate(R.layout.activity_add_fence, null);
		setContentView(mLinearLayout);
		super.onCreate(savedInstanceState);
		

		btnAdd = initMenu(R.string.confirm, new OnClickListener() {
			@Override public void onClick(View arg0) {
				if (validate()) {
					btnAdd.setVisibility(View.GONE);
					showWaitingFlag();

					if (STATE_SAVE.equals(state))
						addFence();
					else if (STATE_UPDATE.equals(state))
						updateFence();
				}
			}
		});

		etFenceName = (EditText) findViewById(R.id.et_fence_name);

		sbDistance = (SeekBar) findViewById(R.id.sb_distance);
		mLinearLayout.setView(sbDistance);
		sbDistance.setMax(seek_bar_progress);
		sbDistance.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override public void onStopTrackingTouch(SeekBar seekBar) {
				if (mDevicePoint != null) {
					currentRadius = sbDistance.getProgress();
					drawFenceOnMap(currentRadius);
				} else {
					setAndShowWaitingMessage(R.string.fence_fence_hint);
				}
			}

			@Override public void onStartTrackingTouch(SeekBar arg0) {
			}

			@Override public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
			}
		});

		mMapView = (MapView) findViewById(R.id.bmap_view);
		hideZoomController();
		mBaiduMap = mMapView.getMap();
		mMarkerOptions = new MarkerOptions();

		mBaiduMap.setOnMapClickListener(new OnMapClickListener() {
			@Override public boolean onMapPoiClick(MapPoi arg0) {
				return false;
			}

			@Override public void onMapClick(LatLng arg0) {
				clearMapTipsMessage();
				mDevicePoint = arg0;
				searchDevicePointOnMap();
				drawFenceOnMap(currentRadius);
			}
		});

		MapStatusUpdate m = MapStatusUpdateFactory.zoomTo(Constants.DEFAULT_ZOOM_LEVEL - 3);
		mBaiduMap.animateMapStatus(m);

	}

	private void clearMapTipsMessage() {
		String msg = txWaitingMessage.getText().toString();
		if (msg.equals(getString(R.string.fence_fence_hint)) || msg.equals(getString(R.string.fail_deivce_position))) {
			txWaitingMessage.setVisibility(View.GONE);
		}
	}

	private void searchDevicePointOnMap() {
		try {
			mMarkerOptions.position(mDevicePoint);
			mMarkerOptions.perspective(true);
			BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.location);
			mMarkerOptions.icon(bitmap);
			mBaiduMap.addOverlay(mMarkerOptions);
			MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(mDevicePoint);
			mBaiduMap.animateMapStatus(mapStatusUpdate);
		} catch (Exception e) {
			DBLDebug.loge("addfence activity - searchDevicePointOnMap() - map error");
		}
	}

	private void drawFenceOnMap(int radius) {
		try {
			int fenceRadius = seek_bar_start + radius;

			mBaiduMap.clear();
			mBaiduMap.addOverlay(mMarkerOptions);

			int strokeColor = Color.parseColor("#07638D");
			int fillColor = Color.parseColor("#99C2E2EF");

			OverlayOptions options = new CircleOptions().center(mDevicePoint).fillColor(fillColor).stroke(new Stroke(2, strokeColor))
					.radius(fenceRadius);
			mBaiduMap.addOverlay(options);
		} catch (Exception e) {
			DBLDebug.loge("addfence activity - drawFenceOnMap() - map error");
		}

		// part 2: reset progress on the seek bar
		sbDistance.setProgress(radius);
	}

	private void hideZoomController() {
		int count = mMapView.getChildCount();
		View zoomView = null;

		for (int i = 0; i < count; i++) {
			View child = mMapView.getChildAt(i);
			if (child instanceof ZoomControls) {
				zoomView = child;
				break;
			}
		}
		zoomView.setVisibility(View.GONE);
	}

	private boolean validate() {
		String fencename = etFenceName.getText().toString().trim();
		if (TextUtils.isEmpty(fencename)) {
			showToast(R.string.fence_name_hint);
			return false;
		}
		if (!fencename.matches(Constants.VALIDATE_NAME)) {
			showToast(R.string.validate_1);
			return false;
		}

		if (mDevicePoint == null) {
			setAndShowWaitingMessage(R.string.fence_fence_hint);
			return false;
		}
		return true;
	}

	private void addFence() {
		String fencename = etFenceName.getText().toString().trim();
		double lon = mDevicePoint.longitude;
		double lat = mDevicePoint.latitude;
		int radius = sbDistance.getProgress() + seek_bar_start;
		ServerApiFactory.getApiImpl().fenceAdd(sign, mdn, fencename, lon, lat, radius, saveOrUpdateCallback);
	}

	private void updateFence() {
		fence.setFence_name(etFenceName.getText().toString().trim());
		fence.setLon(String.valueOf(mDevicePoint.longitude));
		fence.setLat(String.valueOf(mDevicePoint.latitude));
		fence.setRadius(String.valueOf(sbDistance.getProgress() + seek_bar_start));
		ServerApiFactory.getApiImpl().fenceModi(sign, mdn, fence, saveOrUpdateCallback);
	}

	private RequestCallback saveOrUpdateCallback = new RequestCallback() {

		@Override public void onSuccess(String rawData, Object response) {
			BaseResponse baseResponse = (BaseResponse) response;
			String status = baseResponse.getStatus();
			String desc = baseResponse.getDesc();
			if (status.equals(Constants.REQUEST_SUCCESS)) {
				showToast(desc);
				FenceModiActivity.this.finish();
			} else {
				showToast(desc);
				btnAdd.setVisibility(View.VISIBLE);
				hiddenWaitingFlag();
			}
		}

		@Override public void onError(int statusCode, Throwable e, String rawData) {
			btnAdd.setVisibility(View.VISIBLE);
			hiddenWaitingFlag();
		}
	};

	@Override protected void onResume() {
		super.onResume();
		mMapView.onResume();
	}

	@Override protected void onPause() {
		super.onPause();
		mMapView.onPause();
	}

	@Override protected void onDestroy() {
		super.onDestroy();
		mMapView.onDestroy();
	}

	@Override public void finish() {
		super.finish();
		overridePendingTransition(R.anim.keep_original_state, R.anim.slide_out_right);
	}

}
